// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  var retun_msg = [];
  //退出登录
  if(event.exitlogin){
    retun_msg = await db.collection('login_history').where({
      openid: wxContext.OPENID,
    }).remove();
  }else{
    //判断是否为快速登录操作
    if(event.fastlogin){
      await db.collection('login_history').where({
        openid: wxContext.OPENID,
      })
      .get().then(res => {
        if(res.data.length > 0){
          retun_msg = {"error":"0","msg":"登录成功","user_id":res.data[0].user_id,"address1":res.data[0].address1,"address2":res.data[0].address2,"shop":res.data[0].shop,"guest":res.data[0].guest}
        }else{
          retun_msg = {"error":"1","msg":"登录失败,无绑定记录"}
        }
      })
    }else{
      //每次登陆前删除绑定记录
      await  db.collection('login_history').where({
        openid: wxContext.OPENID,
      }).remove()
      //执行登录操作
      await db.collection('Signs').where({
        user: event.user
      })
      .get().then(res => {
        console.log(res);
        if(res.data.length > 0){
          if(res.data[0].password == event.password){
            retun_msg = {"error":"0","msg":"登录成功","user_id":res.data[0]._id,"address1":res.data[0].address1,"address2":res.data[0].address2,"shop":res.data[0].shop}
            //写入绑定数据库
            db.collection('login_history').add({
              data: {
                user:event.user,
                user_id:res.data[0]._id,
                openid:wxContext.OPENID,
                address1:res.data[0].address1,
                address2:res.data[0].address2,
                shop:res.data[0].shop,
                login_time:new Date().toLocaleString(),
                guest:event.guest,
              }
            });
          }else{
            retun_msg = {"error":"1","msg":"用户名或密码不正确"}
          }
        }else{
          retun_msg = {"error":"1","msg":"用户名或密码不正确"}
        }
      });
    }
  }
  return retun_msg;
}